package pl.edu.agh.mobicentsVoIP.core;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;

import javax.servlet.sip.Proxy;
import javax.servlet.sip.SipSession;


import pl.edu.agh.mobicentsVoIP.database.DatabaseItem;

public class Call extends DatabaseItem {


	private User from;
	private User to;
	private CallStatus status;
	private Date startDate;
	private Date endDate;
	private HashSet<SipSession> sessions;
	private Proxy proxy;
	
	public Proxy getProxy() {
		return proxy;
	}

	public void setProxy(Proxy proxy) {
		this.proxy = proxy;
	}

	//Hibernate-purpose constructor
	public Call(){
		sessions = new HashSet<SipSession>();
	}
	
	public User getFrom() {
		return from;
	}
	public void setFrom(User from) {
		this.from = from;
	}
	
	public User getTo() {
		return to;
	}
	public void setTo(User to) {
		this.to = to;
	}
	
	public CallStatus getStatus() {
		return status;
	}
	public void setStatus(CallStatus status) {
		this.status = status;
	}
	
	public void addSession(SipSession session){
		sessions.add(session);
	}
	public void end(){
		if(status == CallStatus.CONNECTED){
			for(SipSession session : sessions){
				try {
	                //session.createRequest("BYE").send();
	                session.getApplicationSession().setInvalidateWhenReady(true);
				} catch (Exception ex) {
	                ex.printStackTrace();
				}
			}
			status = CallStatus.OVER;
		}else{
			status = CallStatus.TERMINATED;
		}
	}

	@Override
	public String toString() {
		return "[" + status + "] from: " 
				+ (from == null? "null" :from.getName()) 
				+ " to: " 
				+ (to==null? "null" :to.getName())
				+" | time: " 
				+ (startDate == null? "null" : date2String(startDate)) 
				+ " - " 
				+ (endDate == null? "null" : date2String(endDate));
	}
	public String getString(){
		return String.format("%s-%s, %s-%s, status: %s", from.getUserURI(), to.getUserURI(), startDate.toString(), endDate.toString() );
	}
	
	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	private String date2String(Date date){
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy");
		return df.format(date);
	}
}
